import { User } from "../../hall/User"
import { ManualMgr } from "../ManualMgr"

/**
 * 观战者
 */
export class Watcher {

    manual:ManualMgr
    user:User
    username:String
    connection

    timer:NodeJS.Timer      //定时200ms向客户端发送消息，定时器
    index:number = 0        //这个观战者读取棋谱内容的索引

    constructor(manual: ManualMgr, user:User) {
        this.manual = manual
        this.user = user
        this.username = user.username
        this.connection = user.connection
        user.watcher = this
        this.manual.addWatcher(this)
        this.startTimer()
    }

    gc() {
        this.manual.watchers.delete(this)
        this.manual = null
        this.user = null
        this.connection = null
        clearInterval(this.timer)
    }

    startTimer() {
        this.timer = setInterval(() => {
            if(this.index == this.manual.list.length-1) {
                clearInterval(this.timer)
                return
            }
            this.sendMessage()
        }, 200)
    }

    update() {
        if(this.index == this.manual.list.length-2) {
            this.sendMessage()
        }
    }

    sendMessage() {
        try {
            let json = this.manual.list[this.index++]
            this.connection.send(json);
        } catch (error) {
            console.error("观战者发送消息失败");
        }
    }
}